import smtplib
import os
import csv

from CacheRankiOS import CacheRankiOS
from CacheRankAndroid import CacheRankAndroid
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def send_mail(ios_csv_path, android_csv_path, infos):
    iosinfo = info["ios"]
    ios_mail_title = iosinfo["mail_title"]
    ios_duration = iosinfo["duration"]
    ios_log_interval = iosinfo["log_interval"]

    androidinfo = infos["android"]
    android_mail_title = androidinfo["mail_title"]
    android_duration = androidinfo["duration"]
    android_log_interval = androidinfo["log_interval"]

    # 账号信息
    account = "xiaodong32@staff.sina.com.cn"
    password = "Woai710104!"
    receivers = "xiaodong32@staff.sina.com.cn,panhao@staff.sina.com.cn,liangliang22@staff.sina.com.cn,hailong9@staff.sina.com.cn"
    to_addrs = receivers.split(",")
    print("构建参数to_addrs:", to_addrs)

    ios_html_table = ""
    android_html_table = ""
    # 构建正文
    # 转换CSV数据为HTML表格
    # iOS
    if os.path.exists(ios_csv_path):
        with open(ios_csv_path, 'r') as file:
            reader = csv.reader(file)
            csv_data = list(reader)

            ios_html_table = '<table style="border-collapse: collapse;">'  # 添加样式来设置边框合并
            ios_html_table += '<tr>'
            for col in csv_data[0]:
                ios_html_table += f'<th style="border: 1px solid black; padding: 8px;">{col}</th>'  # 添加样式来设置表头边框和内边距
            ios_html_table += '</tr>'
            for row in csv_data[1:]:
                ios_html_table += '<tr>'
                for col in row:
                    ios_html_table += f'<td style="border: 1px solid black; padding: 8px;">{col}</td>'  # 添加样式来设置单元格边框和内边距
                ios_html_table += '</tr>'
            ios_html_table += '</table>'

    # Android
    if os.path.exists(android_csv_path):
        with open(android_csv_path, 'r') as file:
            reader = csv.reader(file)
            csv_data = list(reader)

            android_html_table = '<table style="border-collapse: collapse;">'  # 添加样式来设置边框合并
            android_html_table += '<tr>'
            for col in csv_data[0]:
                android_html_table += f'<th style="border: 1px solid black; padding: 8px;">{col}</th>'  # 添加样式来设置表头边框和内边距
            android_html_table += '</tr>'
            for row in csv_data[1:]:
                android_html_table += '<tr>'
                for col in row:
                    android_html_table += f'<td style="border: 1px solid black; padding: 8px;">{col}</td>'  # 添加样式来设置单元格边框和内边距
                android_html_table += '</tr>'
            android_html_table += '</table>'
    ios_html_table = ios_html_table if ios_html_table != '' else '无数据'
    android_html_table = android_html_table if android_html_table != '' else '无数据'
    # howmany = "无差别统计"
    howmany = "微博占用大小大于1G的日志"
    body = f"""
    <html>
    <head></head>
    <body>
        <h1>缓存排名-日常监控</h2>
        <hr>
        <h2>iOS - {ios_duration}</h3>
        <h3>每{ios_log_interval / 60}分钟拉取一次 {howmany} 一次1000条 取前20名</h3>
        <h4>{ios_mail_title}</h4>
        {ios_html_table}
        
        <hr>
        
        <h2>Android - {android_duration}</h2>
        <h3>每{android_log_interval / 60}分钟拉取一 {howmany} 一次1000条 取前20名</h3>
        <h4>{android_mail_title}</h4>
        {android_html_table}
        
        <hr>
        <p>如有问题请联系xiaodng32@</p>
    </body>
    </html>
    """

    # 构造附件
    ios_csv_attachment = MIMEText(str(open(ios_csv_path, "rb").read()), 'base64', 'utf-8')
    ios_csv_attachment['Content-Type'] = 'application/octet-stream'
    ios_csv_attachment['Content-Disposition'] = 'attachment;filename="ios_result.csv"'

    android_csv_attachment = MIMEText(str(open(ios_csv_path, "rb").read()), 'base64', 'utf-8')
    android_csv_attachment['Content-Type'] = 'application/octet-stream'
    android_csv_attachment['Content-Disposition'] = 'attachment;filename="android_result.csv"'

    # 构造消息体
    message = MIMEMultipart()
    message['From'] = account
    message['To'] = receivers
    message['Subject'] = '缓存日常排名监测--测试'
    message.attach(MIMEText(body, 'html', 'utf-8'))
    message.attach(ios_csv_attachment)
    message.attach(android_csv_attachment)
    # 邮件配置
    smtpObj = smtplib.SMTP('mail.staff.sina.com.cn')
    smtpObj.login(account, password)
    err = smtpObj.sendmail(account, to_addrs, message.as_string())
    if err:
        print("邮件发送失败:", err)
    else:
        print("======邮件发送成功======")


if __name__ == '__main__':
    ios_info = CacheRankiOS().fetch()
    android_info = CacheRankAndroid().fetch()
    info = {}
    if ios_info:
        info["ios"] = ios_info
    if android_info:
        info["android"] = android_info
    iOS_CSV_FILE_PATH = ios_info["csv"]
    Android_CSV_FILE_PATH = android_info["csv"]
    send_mail(iOS_CSV_FILE_PATH, Android_CSV_FILE_PATH, info)
